﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;


namespace AutoUpgradeManager.ControlForm
{

    /// <summary>
    /// Window_ServiceSetup.xaml 的交互逻辑
    /// </summary>
    public partial class Window_ServiceSetup : Window
    {
        /// <summary>
        /// 数据集合对象
        /// </summary>
        private ObservableCollection<ProjectInfo> Items;

        /// <summary>
        /// WebService服务客户端对象
        /// </summary>
        public AutoUpdateService.AutoUpdateClient Client
        {
            private get;
            set;
        }

        public Window_ServiceSetup()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(Window_ServiceSetup_Loaded);


        }

        /// <summary>
        /// 窗体加载，获取项目信息列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_ServiceSetup_Loaded(object sender, RoutedEventArgs e)
        {
            Items = new ObservableCollection<ProjectInfo>();

            Lvw_Info.ItemsSource = Items;


            Items.Clear();

            try
            {
                string[] arr = Client.GetPrjNames();            //获取项目名称列表

                foreach (string s in arr)
                {
                    Items.Add(new ProjectInfo(s, Client.GetProjectPath(s)));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 工具条按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolBarButtn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn == null) return;

            Setpanel.Visibility = System.Windows.Visibility.Collapsed;
            SetTextBinding(false);               //设置文本内容取消绑定

            switch (btn.Name.ToLower())
            {
                case "add":
                    Txt_Name.Text = Txt_Path.Text = "";
                    Txt_Name.IsReadOnly = false;
                    Btn_Add.Content = "添加";
                    Setpanel.Visibility = System.Windows.Visibility.Visible;
                    break;
                case "edit":
                    if (Lvw_Info.SelectedItem == null) return;
                    Txt_Name.IsReadOnly = true;
                    SetTextBinding(true);                   //设置文本内容绑定
                    Btn_Add.Content = "修改";
                    Setpanel.Visibility = System.Windows.Visibility.Visible;
                    break;
                case "delete":
                    if (Lvw_Info.SelectedItem == null) return;
                    DeleteProject((ProjectInfo)Lvw_Info.SelectedItem);
                    break;
                case "close":
                    this.Close();
                    break;
            }
            e.Handled = true;
        }



        private void DeleteProject(ProjectInfo item)
        {
            if (MessageBox.Show(string.Format("确认要删除项目【{0}】吗？", item.PrjName), "删除询问", MessageBoxButton.OKCancel, MessageBoxImage.Question)== MessageBoxResult.Cancel) return;
            try
            {
                if (!Client.DeleteProject(item.PrjName, "ChengDuClou"))
                {
                    MessageBox.Show(string.Format("删除项目【{0}】失败", item.PrjName), "删除失败", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\r\n" + e.StackTrace, "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            
            Items.Remove(item);
        }


        /// <summary>
        /// 设置文本框是否绑定
        /// </summary>
        /// <param name="IsBinding"></param>
        private void SetTextBinding(bool IsBinding)
        {
            if (IsBinding)
            {
                Binding binding = new Binding("PrjName");

                binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;

                Txt_Name.SetBinding(TextBox.TextProperty, binding);

                binding = new Binding("PrjPath");

                binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;


                Txt_Path.SetBinding(TextBox.TextProperty, binding);
            }
            else
            {
                BindingOperations.ClearBinding(Txt_Name, TextBox.TextProperty);
                BindingOperations.ClearBinding(Txt_Path, TextBox.TextProperty);
            }
        }


        /// <summary>
        /// 添加项目配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Add_Click(object sender, RoutedEventArgs e)
        {
            #region -------------文本数据信息验证判断----------------------
            if (Txt_Name.Text.Trim() == "")
            {
                MessageBox.Show("请输入正确的项目名称...", "错误", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            if (Txt_Path.Text.Trim() == "")
            {
                MessageBox.Show("请输入正确的项目路径...", "错误", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            else
            {
                string path = Txt_Path.Text.Trim();

                if (path.Where((c)=>c==':').Count()>0)
                {
                    MessageBox.Show("请输入正确的项目路径,项目路径为相对路径...", "错误", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
            }
            #endregion

            try
            {
                if (!Client.SetProject(Txt_Name.Text, Txt_Path.Text, "WinAhriman"))          //设置项目信息（项目名称，路径）
                {
                    MessageBox.Show("项目配置设置失败...", "服务错误", MessageBoxButton.OK, MessageBoxImage.Information);
                    return ;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "服务错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return ;
            }


            if (Btn_Add.Content.ToString() == "添加")         //添加项目信息
            {
                Items.Add(new ProjectInfo(Txt_Name.Text.Trim(), Txt_Path.Text.Trim()));
            }
            else
            {
                BindingExpression be= BindingOperations.GetBindingExpression(Txt_Name, TextBox.TextProperty);           //更新项目信息

                if (be != null) be.UpdateSource();

                be = BindingOperations.GetBindingExpression(Txt_Path, TextBox.TextProperty);

                if (be != null) be.UpdateSource();
                
            }

            Setpanel.Visibility = System.Windows.Visibility.Collapsed;
            e.Handled = true;
        }


        /// <summary>
        /// 关闭项目配置面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            Setpanel.Visibility = System.Windows.Visibility.Collapsed;
            e.Handled = true;
        }
    }

    internal class ProjectInfo : DependencyObject
    {

        public static DependencyProperty PrjNameProperty = DependencyProperty.Register("PrjName", typeof(string), typeof(ProjectInfo));
        public static DependencyProperty PrjPathProperty = DependencyProperty.Register("PrjPath", typeof(string), typeof(ProjectInfo));

        public string PrjName
        {
            get
            {
                return (string)this.GetValue(PrjNameProperty);
            }
            set
            {
                this.SetValue(PrjNameProperty, value);
            }
        }

        public string PrjPath
        {
            get
            {
                return (string)this.GetValue(PrjPathProperty);
            }
            set
            {
                this.SetValue(PrjPathProperty, value);
            }
        }

        public ProjectInfo(string prjname, string prjpath)
        {
            PrjName = prjname;

            PrjPath = prjpath;
        }

    }
}
